import type { Position } from '@turf/turf'
import type { LoadingInstance } from 'element-plus/es/components/loading/src/loading'
import type {
  AssetHomeMarkerData,
  AssetHomeMapPropsType,
  AssetHomeMapStateType
  // LoopInfoMapMarkerEventType
} from './typings'
import { defineComponent, ref, reactive, onMounted, onBeforeUnmount, shallowRef } from 'vue'
import { useStore } from 'vuex'
import {
  keys as Keys
  // values as Values
} from 'lodash'
import { lineString, bbox, randomPoint, polygon, booleanPointInPolygon } from '@turf/turf'
import { ElLoading } from 'element-plus'
import useAMap from '~/hooks/useAMap'
import styles from '../../index.module.scss'

export default defineComponent({
  name: 'AssetHomeMap',
  props: [
    'id',
    'initCallback',
    'patternData',
    // 'areaInfoVisible',
    'activeModules',
    'patternMarkerType',
    'getMapZoom',
    'activeOptionsBar'
  ],
  emits: [
    // 'changeAreaInfoView',
    // 'changeAreaInfoPosition',
    'changePatterMarkerInfoView',
    'changePatterMarkerInfoPosition',
    'changeLoopInfoView',
    'changePatterPolylineInfoView'
  ],
  setup(props: AssetHomeMapPropsType, { emit, expose }) {
    const store = useStore()
    const loadRef = ref<LoadingInstance>()
    const mapDomRef = ref()
    const state = reactive<AssetHomeMapStateType>({
      mapCenter: [],
      polygon: {},
      areaCenterMarker: {},
      patternMarker: {},
      patternPolyline: {},
      activePatternPolylineId: {},
      lamppostMarker: {},
      lampMarker: {},
      lampTitleMarker: {},
      distributionMarker: {}
    })
    // const distributionBool = ref(true)
    const lamppost = shallowRef()
    const lamp = shallowRef()
    const lamptitle = shallowRef()
    const distribution = shallowRef()
    const [mapRef, aMapRef, amapIconRef] = useAMap(
      props.id,
      {
        zoom: 11,
        showIndoorMap: false,
        showLabel: true
        // viewMode: '2D',
        // baseRender: 'd',
      },
      initAMap
    )

    // 随机获取地图面中包含的点
    const handleGetMapRandomPoint = (
      lineStringData: number[],
      onePolygonData: number[]
    ): [number, number] => {
      const turfLineString = lineString(lineStringData as unknown as Position[])
      const turfBbox = bbox(turfLineString)
      const turfPolygon = polygon(onePolygonData as unknown as Position[][])
      let turfRandomPoint = randomPoint(1, { bbox: turfBbox })
      while (!booleanPointInPolygon(turfRandomPoint.features[0], turfPolygon)) {
        turfRandomPoint = randomPoint(1, { bbox: turfBbox })
      }
      return turfRandomPoint.features[0].geometry.coordinates as [number, number]
    }

    // 根据父组建请求接口返回的生成地图图标配置
    const handleGenerateMarkerIcon = (optionsBar: AssetHomeMapPropsType['optionsBar']) => {
      state.loopOptions = {}
      state.markerIconOptions = optionsBar?.reduce(
        (markerIconOptions: AssetHomeMapStateType['markerIconOptions'], item) => {
          const { patternData } = props
          if (!patternData) return markerIconOptions
          // 是回路时跳过回路遍历
          if (item.code === 'DistributionLoop') {
            state.loopOptions![item.id] = {
              key: patternData![item.id].modelConfigDataVO?.renderer?.categoryList?.[0]?.select,
              legend: patternData![item.id].modelConfigDataVO?.base?.legend,
              zooms: patternData![item.id].modelConfigDataVO?.base?.maxScale
                ? [
                    patternData![item.id].modelConfigDataVO?.base?.minScale,
                    Math.floor(patternData![item.id].modelConfigDataVO?.base?.maxScale) + 0.9
                  ]
                : [],
              settings: patternData![item.id].modelConfigDataVO?.renderer?.categoryList?.reduce(
                (markerItemOption: Record<string, Record<string, any>>, childItem) => {
                  markerItemOption[childItem.value] = {
                    color: childItem.color,
                    lineColor: childItem.lineColor,
                    lineWidth: childItem.lineWidth,
                    lineOpacity: childItem.lineOpacity,
                    selectLineColor:
                      patternData![item.id].modelConfigDataVO?.select?.selectLineColor,
                    selectLineWidth:
                      patternData![item.id].modelConfigDataVO?.select?.selectLineWidth
                  }
                  return markerItemOption
                },
                {}
              )
            }
            return markerIconOptions
          }
          // 记录下灯杆的moduleId在绘制灯的时候需要用到
          if (item.code === 'LampPost') state.lampPostModuleId = item.id
          markerIconOptions![item.id] = {
            key: patternData![item.id].modelConfigDataVO?.renderer?.categoryList?.[0]?.select,
            isTag: patternData![item.id].modelConfigDataVO?.base?.isTag,
            tagName: patternData![item.id].modelConfigDataVO?.base?.tagName,
            legend: patternData![item.id].modelConfigDataVO?.base?.legend,
            infoVisible: patternData![item.id].modelConfigDataVO?.info?.infoVisible,
            zooms: patternData![item.id].modelConfigDataVO?.base?.maxScale
              ? [
                  patternData![item.id].modelConfigDataVO?.base?.minScale,
                  Math.floor(patternData![item.id].modelConfigDataVO?.base?.maxScale) + 0.9
                ]
              : [],
            icons: patternData![item.id].modelConfigDataVO?.renderer?.categoryList?.reduce(
              (markerItemOption: Record<string, Record<string, any>>, childItem) => {
                markerItemOption[childItem.value] = {
                  width: childItem.iconWidth,
                  height: childItem.iconLength,
                  iconUrl: childItem.iconImageBase,
                  iconSize: [childItem.iconWidth, childItem.iconLength],
                  offset: [0, -childItem.iconLength],
                  bigVisible: patternData![item.id].modelConfigDataVO?.select?.selectVisible,
                  bigWidth: patternData![item.id].modelConfigDataVO?.select?.selectIconWidth,
                  bigHeight: patternData![item.id].modelConfigDataVO?.select?.selectIconLength,
                  bigIconSize: [
                    patternData![item.id].modelConfigDataVO?.select?.selectIconWidth,
                    patternData![item.id].modelConfigDataVO?.select?.selectIconLength
                  ],
                  bigOffset: [
                    0,
                    -patternData![item.id].modelConfigDataVO?.select?.selectIconLength +
                      childItem.iconLength
                  ]
                }
                return markerItemOption
              },
              {}
            )
          }
          return markerIconOptions
        },
        {}
      )
    }

    // 恢复地图默认中心点
    const handleRestMapCenter = () => {
      mapRef.value.setCenter(state.mapCenter)
    }

    // 设置地图信息
    const handleSetMapInfo = (mapData: Record<string, any>) => {
      if (mapRef.value && mapData) {
        state.mapCenter = [mapData.lon, mapData.lat]
        // 设置地图中心点和地图层级
        mapRef.value.setZoomAndCenter(mapData.layerLevel, state.mapCenter, false, 0)

        props.getMapZoom?.()
      }
    }

    // 清除地图绑定详情弹框事件
    const handleClearActiveMarkerEvent = () => {
      state.activeMarker = undefined
      // 如果当前的图标有放大的话 则清除放大状态
      // 如果当前的选中的图案放大了 则缩小 如果没放大 则不执行if操作
      const activeMarkerExtData = state.activePatternMarker?.getExtData?.()
      const activeMarker =
        state.patternMarker?.[activeMarkerExtData?.moduleId]?.[activeMarkerExtData?.id]
      if (state.activePatternMarker && activeMarker && activeMarkerExtData?.active) {
        activeMarker?.setExtData({ ...(activeMarker?.getExtData() || []), active: true })
        handleChangeEnlargeMarker({ target: activeMarker })
      }
      // if (state.activePatternMarker)
      //   handleChangeEnlargeMarker({ target: state.activePatternMarker })
      state.activePatternMarker = undefined
      // emit('changeAreaInfoView', 0, 0, undefined, undefined)
      emit('changePatterMarkerInfoView')
      mapRef.value.clearEvents('mapmove')
      mapRef.value.clearEvents('resize')
      mapRef.value.clearEvents('moveend')
      // 继续为地图绑定拖拽结束事件  结束后要去触发请求 查询当前显示区域内的所有选中的值
      mapRef.value.on('moveend', handleSearchMapMarkerByModuleId)
    }

    // 生成工区
    const handleGeneratePolygon = (polygonData: Record<string, any>) => {
      let position
      try {
        if (!polygonData.centerPoint) throw new Error()
        position = JSON.parse(polygonData.centerPoint)
      } catch (error) {
        // 当是多面时逻辑 默认取第一个
        if (polygonData?.phaseType === 'MultiPolygon' && polygonData.coordinates?.length) {
          position = handleGetMapRandomPoint(
            polygonData.coordinates[0][0],
            polygonData.coordinates[0]
          )
        } else if (polygonData.coordinates?.length) {
          // 挖洞面解析
          position = handleGetMapRandomPoint(polygonData.coordinates[0], polygonData.coordinates)
        }
      }

      // 如果面已经存在 则更新位置信息
      if (state.polygon[polygonData.id]) {
        state.polygon[polygonData.id].setPath(polygonData.coordinates)
        if (position) {
          state.areaCenterMarker[polygonData.id].setPosition(position)
        } else {
          state.areaCenterMarker[polygonData.id].setPosition(
            state.polygon[polygonData.id]?.getBounds?.()?.getCenter?.()
          )
        }
        return
      }
      // 工区面
      state.polygon[polygonData.id] = new aMapRef.value.Polygon({
        map: mapRef.value,
        path: polygonData.coordinates,
        fillColor: polygonData.backColor,
        strokeColor: polygonData.bordeColor,
        strokeWeight: polygonData.width ?? 1,
        zooms: polygonData.minZoom ? [polygonData.minZoom, polygonData.maxZoom] : [],
        bubble: true,
        extData: polygonData
      })

      state.areaCenterMarker[polygonData.id] = new aMapRef.value.Text({
        map: mapRef.value,
        position: position || state.polygon[polygonData.id]?.getBounds?.()?.getCenter?.(),
        zooms: polygonData.minZoom ? [polygonData.minZoom, polygonData.maxZoom] : [],
        text: polygonData.assetModelInfoDataVO?.infoList
          ? `
          <section class="area-info-title">${polygonData.name}</section>
          <section class="area-info-content">
            ${
              polygonData.assetModelInfoDataVO?.infoList
                ?.map(
                  (item: Record<string, string>) => `<p>${item.key || ''}: ${item.value || ''}</p>`
                )
                ?.join('') || ''
            }
          </section>
        `
          : `<section class="area-info-title">${polygonData.name}</section>`
      })
    }

    /**
     * 切换某个工区的展示和隐藏
     * 同时切换工区点和工区面 并将地图定位到当前选中的工区和最大层级
     * @param id 工区id
     * @param visible 展示/隐藏  (暂时废弃)
     */
    const handleChangePolygonVisible = async (id: string, visible: boolean) => {
      if (id && state.polygon[id]) {
        const { patternData } = props
        const araeData = state.polygon[id].getExtData()
        if (visible) {
          const selectData = patternData![araeData.moduleId].modelConfigDataVO?.select
          await mapRef.value.setZoomAndCenter(
            araeData?.minZoom ?? mapRef.value.getZoom(),
            state.areaCenterMarker[id]?.getPosition(),
            false,
            0
          )

          // 设置选中面边框加粗
          state.polygon[id].setOptions({
            strokeWeight: selectData.selectLineWidth
          })
          // state.polygon[id].show()
          // state.areaCenterMarker[id].show()
          handleSearchMapMarkerByModuleId()
          return
        } else {
          // 还原选中面
          state.polygon[id].setOptions({
            strokeWeight: araeData.width ?? 1
          })
        }
        // 如果有当前的点击的坐标点 则清除
        if (state.activeMarker?.getExtData?.()?.id === id) handleClearActiveMarkerEvent()
        // state.polygon[id].hide()
        // state.areaCenterMarker[id].hide()
      }
    }

    // 根据传入的工区id数组展示对应id的工区面其他的则隐藏
    const handleShowAreaPolygonByAreaId = (ids: string[]) => {
      Keys(state.polygon)?.forEach((key: string) => {
        if (ids?.includes(key)) {
          state.polygon[key]?.show()
          state.areaCenterMarker[key]?.show()
        } else {
          state.polygon[key]?.hide()
          state.areaCenterMarker[key]?.hide()
        }
      })
    }

    // 获取事件源中的坐标点并放大
    const handleChangeEnlargeMarker = (markerEvent: Record<string, any>) => {
      const extData = markerEvent.target.getExtData()
      extData.active = !extData.active
      const iconSetting =
        state.markerIconOptions![extData.moduleId]?.icons[
          extData?.[state.markerIconOptions![extData.moduleId].key as keyof AssetHomeMarkerData]
        ]
      if (!iconSetting.bigVisible) return
      const showMarker = state.patternMarker![extData.moduleId][extData.id]
      if (extData.active) {
        showMarker.setIcon({
          size: iconSetting.bigIconSize
        })
      } else {
        showMarker.setIcon({
          size: iconSetting.iconSize
        })
      }
      markerEvent.target.setExtData(extData)
    }

    // 根据传入类型判断选择什么接口请求详情数据
    const handleGetPatterMarkerInfoBy = async (extData: AssetHomeMarkerData) => {
      let markerType = ''
      const result = await store.dispatch('assetHome/GetAssetHomePopoverInfoDataById', {
        assetId: extData?.id,
        specialCode: 'asset_home'
      })
      // 当是配电设施时
      if (result?.data?.moduleCode === 'Distribution') {
        markerType = 'facility'
      } else if (result?.data?.moduleCode === 'LampPost') {
        // 当是灯杆时
        markerType = 'lightPole'
      } else if (result?.data?.moduleCode === 'LampBase') {
        // 当是灯时
        markerType = 'lamp'
      }
      if (result?.data?.assetId && markerType) {
        // 并查询是否有重叠点 如果有则一并返回
        if (extData.phase.type === 'point' && extData.phase.coordinates.length >= 2) {
          const res = await store.dispatch('assetHome/GetAssetHomeOverlapPointList', {
            lon: extData.phase.coordinates[0],
            lat: extData.phase.coordinates[1]
          })
          return {
            markerType,
            data: result?.data,
            pointList: res?.data || []
          }
        }

        return {
          markerType,
          data: result?.data
        }
      }
      return {
        markerType: undefined,
        data: undefined
      }
    }

    // 根据传入配电设施数据查询关联回路灯灯杆信息
    const handleGetPatterPolylineInfoByDistributionId = async (extData: AssetHomeMarkerData) => {
      const result = await store.dispatch(
        'powerDistributionFacilities/GetAssociativeLoopInfoByDistributionId',
        {
          id: extData?.id
        }
      )
      return result?.data
    }

    // 配电设施/灯杆/灯 地图拖拽时的回调
    const handleReplacePatterDomOffset = () => {
      const mapClientRect = mapDomRef.value.getBoundingClientRect()
      const patternMarkerOffset = mapRef.value.lngLatToContainer(
        state.activePatternMarker!.getPosition()
      )
      if (mapClientRect && patternMarkerOffset) {
        // 将获取到的 left top 和 工区数据发送给父组建
        emit(
          'changePatterMarkerInfoPosition',
          patternMarkerOffset.x + mapClientRect.left,
          patternMarkerOffset.y + mapClientRect.top - 2
        )
      }
    }

    // 配电设施/灯杆/灯 地图拖拽结束的回调
    const handleJudgeActivePatterMarkerInMap = async () => {
      if (!mapRef.value.getBounds().contains(state.activePatternMarker?.getPosition())) {
        emit('changePatterMarkerInfoView')
      } else if (!props.patternMarkerType) {
        const mapClientRect = mapDomRef.value.getBoundingClientRect()
        const patternMarkerOffset = mapRef.value.lngLatToContainer(
          state.activePatternMarker!.getPosition()
        )
        const { markerType, data, pointList } = await handleGetPatterMarkerInfoBy(
          state.activePatternMarker?.getExtData()
        )
        if (mapClientRect && patternMarkerOffset) {
          // 将获取到的 left top 和 工区数据发送给父组建
          emit(
            'changePatterMarkerInfoView',
            patternMarkerOffset.x + mapClientRect.left,
            patternMarkerOffset.y + mapClientRect.top - 2,
            markerType,
            data,
            pointList
          )
        }
      }
    }

    // 点击配电设施/灯杆/灯回调
    const handleClickPatterMarker = async (markerEvent: Record<string, any>) => {
      const extData = markerEvent.target.getExtData()
      if (state.activePatternMarker?.getExtData?.()?.id !== extData?.id) {
        if (state.markerIconOptions![extData.moduleId]?.infoVisible === 0) return
        // 先清除所有事件 防治其他的弹框影响
        handleClearActiveMarkerEvent()
        await handleSearchMapMarkerByModuleId()
        const mapClientRect = mapDomRef.value.getBoundingClientRect()
        const patternMarkerOffset = mapRef.value.lngLatToContainer(
          markerEvent.target!.getPosition()
        )
        // 将获取到的 left top 和 工区数据发送给父组建
        const { markerType, data, pointList } = await handleGetPatterMarkerInfoBy(extData)
        if (!data) return
        state.activePatternMarker = markerEvent.target

        handleChangeEnlargeMarker({ target: state.activePatternMarker })
        emit(
          'changePatterMarkerInfoView',
          patternMarkerOffset.x + mapClientRect.left,
          patternMarkerOffset.y + mapClientRect.top - 2,
          markerType,
          data,
          pointList
        )
        // 给map注册拖动事件 让popover 随着拖动移动
        mapRef.value.on('mapmove', handleReplacePatterDomOffset)
        mapRef.value.on('resize', handleReplacePatterDomOffset)
        mapRef.value.on('moveend', handleJudgeActivePatterMarkerInMap)
        return
      }
      // 如果当前的选中的图案放大了 则缩小 如果没放大 则不执行if操作
      if (state?.activePatternMarker?.getExtData?.()?.active)
        handleChangeEnlargeMarker({ target: state.activePatternMarker })
      state.activePatternMarker = undefined
      handleClearActiveMarkerEvent()
      emit('changePatterMarkerInfoView')
    }

    // 每次拖拽结束后判断回路弹框是否在可视区域内  如果不在则关闭弹框
    const handleJudgeActiveLoopInfoInMap = async () => {
      if (!mapRef.value.getBounds().contains(state.activePatternMarker?.getPosition())) {
        emit('changePatterPolylineInfoView')
      } else if (!props.patternMarkerType) {
        const mapClientRect = mapDomRef.value.getBoundingClientRect()
        const patternMarkerOffset = mapRef.value.lngLatToContainer(
          state.activePatternMarker!.getPosition()
        )
        const extData = state.activePatternMarker?.getExtData()
        const data = await handleGetPatterPolylineInfoByDistributionId(extData)
        if (mapClientRect && patternMarkerOffset) {
          // 将获取到的 left top 和 工区数据发送给父组建
          emit(
            'changePatterPolylineInfoView',
            patternMarkerOffset.x + mapClientRect.left,
            patternMarkerOffset.y + mapClientRect.top - 2,
            extData.name,
            data,
            state.activePatternPolylineId[extData.id]
          )
        }
      }
    }

    // 点击配电设施右键回调
    const handleRightClickPatterMarker = async (markerEvent: Record<string, any>) => {
      const extData = markerEvent.target.getExtData()
      if (state.activePatternMarker?.getExtData?.()?.id !== extData?.id) {
        if (state.markerIconOptions![extData.moduleId]?.infoVisible === 0) return
        // 先清除所有事件 防治其他的弹框影响
        handleClearActiveMarkerEvent()
        mapRef.value.setCenter(markerEvent.target!.getPosition(), false, 0)
        await handleSearchMapMarkerByModuleId()

        const mapClientRect = mapDomRef.value.getBoundingClientRect()
        const patternMarkerOffset = mapRef.value.lngLatToContainer(
          markerEvent.target!.getPosition()
        )

        const data = await handleGetPatterPolylineInfoByDistributionId(extData)
        if (!data) return
        state.activePatternMarker = markerEvent.target
        handleChangeEnlargeMarker({ target: state.activePatternMarker })
        // 如果当前配电设施下没有任何灯杆数据且为空时 创建一个空数组
        if (!state.activePatternPolylineId?.[extData?.id])
          state.activePatternPolylineId[extData.id] = []
        emit(
          'changePatterPolylineInfoView',
          patternMarkerOffset.x + mapClientRect.left,
          patternMarkerOffset.y + mapClientRect.top - 2,
          extData.name,
          data,
          state.activePatternPolylineId[extData.id]
        )
        // 给map注册拖动事件 让popover 随着拖动移动  拖动移动可与上面的共用
        mapRef.value.on('mapmove', handleReplacePatterDomOffset)
        mapRef.value.on('resize', handleReplacePatterDomOffset)
        mapRef.value.on('moveend', handleJudgeActiveLoopInfoInMap)
        return
      }
      // 如果当前的选中的图案放大了 则缩小 如果没放大 则不执行if操作
      if (state?.activePatternMarker?.getExtData?.()?.active)
        handleChangeEnlargeMarker({ target: state.activePatternMarker })
      state.activePatternMarker = undefined
      handleClearActiveMarkerEvent()
      emit('changePatterPolylineInfoView')
    }

    // 根据传入的折线对象和选中状态来切换选中样式
    const handleChangePatternPolylineActiveStyle = (
      active: boolean,
      patternPolyline: Record<string, any>
    ) => {
      const extData = patternPolyline.getExtData()
      const loopKeyValue = state.loopOptions![extData.moduleId]?.key as keyof AssetHomeMarkerData
      patternPolyline.setOptions({
        strokeColor:
          state.loopOptions![extData.moduleId]?.settings[extData?.[loopKeyValue]]?.lineColor,
        strokeWeight: active
          ? state.loopOptions![extData.moduleId]?.settings[extData?.[loopKeyValue]]?.selectLineWidth
          : state.loopOptions![extData.moduleId]?.settings[extData?.[loopKeyValue]]?.lineWidth
      })
    }

    // 点击回路回调
    const handleClickPatternPolyline = async (polylineEvent: Record<string, any>) => {
      if (state.activePatternMarker) {
        if (state?.activePatternMarker?.getExtData?.()?.active)
          handleChangeEnlargeMarker({ target: state.activePatternMarker })
        state.activePatternMarker = undefined
        handleClearActiveMarkerEvent()
        emit('changePatterPolylineInfoView')
      }

      const extData = polylineEvent.target.getExtData()
      const res = await store.dispatch('loopMonitoringBox/GetDistributionIdByLoopId', {
        id: extData?.id
      })
      if (!res?.data) return
      if (!state.activePatternPolylineId[res?.data as string])
        state.activePatternPolylineId[res?.data as string] = []
      if (!state.activePatternPolylineId[res?.data as string]?.includes(extData?.id)) {
        handleChangePatternPolylineActiveStyle(true, polylineEvent.target)
        state.activePatternPolylineId[res?.data as string].push(extData?.id)
        return
      }
      handleChangePatternPolylineActiveStyle(false, polylineEvent.target)
      state.activePatternPolylineId[res?.data as string] = state.activePatternPolylineId[
        res?.data as string
      ]?.filter((item) => item !== extData?.id)
    }

    // 更新回路选中事件
    const handleChangeActivePatternPolyline = (ids: string[], distributionId?: string) => {
      const usedDistributionId = distributionId || state.activePatternMarker?.getExtData?.()?.id
      const nextActiveIds = ids?.filter(
        (item) => !state.activePatternPolylineId[usedDistributionId]?.includes(item)
      )
      const nextCancelIds = state.activePatternPolylineId[usedDistributionId]?.filter(
        (item) => !ids?.includes(item)
      )
      // 把当前新增选中的 图形状态改为选中
      nextActiveIds?.forEach((item) => {
        if (state.patternPolyline![item])
          handleChangePatternPolylineActiveStyle(true, state.patternPolyline![item])
      })
      // 把当前取消选中的 图形状态改为未选中
      nextCancelIds?.forEach((item) => {
        if (state.patternPolyline![item])
          handleChangePatternPolylineActiveStyle(false, state.patternPolyline![item])
      })
      state.activePatternPolylineId[usedDistributionId] = ids
      return state.activePatternPolylineId[usedDistributionId]
    }

    //  绘制线
    // const handPolyline = async (patternList: Record<string, any>[]) => {
    //   if (!patternList?.length || !state.markerIconOptions) return
    //   const activeLoopIds = JSON.stringify(state.activePatternPolylineId)
    //   const patternPolyline: AssetHomeMapStateType['patternPolyline'] = {}
    //   const { patternData } = props
    //   if (!patternData) return
    //   state.patternMarker = patternList?.reduce(
    //     (patternMarker: AssetHomeMapStateType['patternMarker'], item: Record<string, any>) => {
    //       const phase = item.phase ? item.phase : null
    //       // 当没有配置经纬度路经点时则不去生成图形
    //       if (!phase) return patternMarker
    //       if (phase.type === 'polyline' || phase.type === 'multiPolyline') {
    //         // 判断配置绘制层级
    //         // if(moduleId == null){
    //         //   moduleId = item.moduleId;
    //         // }

    //         const loopKeyValue = state.loopOptions![item.moduleId]?.key as keyof AssetHomeMarkerData

    //         // 找不到匹配的折线配置就return
    //         if (!loopKeyValue) return patternMarker
    //         const activeFlag = activeLoopIds?.includes(item.id)
    //         const polyline = new aMapRef.value.Polyline({
    //           // map: mapRef.value,
    //           path: phase.coordinates || [],
    //           title: item?.name,
    //           cursor: 'pointer',
    //           lineJoin: 'round',
    //           lineCap: 'round',
    //           strokeColor:
    //             state.loopOptions![item.moduleId]?.settings[item?.[loopKeyValue]]?.lineColor,
    //           strokeOpacity:
    //             state.loopOptions![item.moduleId]?.settings[item?.[loopKeyValue]]?.lineOpacity,
    //           strokeWeight: activeFlag
    //             ? state.loopOptions![item.moduleId]?.settings[item?.[loopKeyValue]]?.selectLineWidth
    //             : state.loopOptions![item.moduleId]?.settings[item?.[loopKeyValue]]?.lineWidth,
    //           zooms:
    //             state.loopOptions![item.moduleId].zooms?.length &&
    //             state.loopOptions![item.moduleId].zooms,
    //           extData: item
    //         })
    //         patternPolyline![item.id] = polyline
    //         // polyline.on('click', handleClickPatternPolyline)
    //         return patternMarker
    //       }

    //       return patternMarker
    //     },
    //     {}
    //   )

    //   state.patternPolyline = patternPolyline

    //   // 清理线并重新添加进图层展示
    //   const patternPolylineList = Values(state.patternPolyline)
    //   if (patternPolylineList?.length) {
    //     state.lineGroup = new aMapRef.value.OverlayGroup(patternPolylineList)
    //     mapRef.value.add(state.lineGroup)
    //   }
    // }

    //  绘制配电设施
    // const distributionDraw = async (patternList: Record<string, any>[]) => {
    //   if (!patternList?.length || !state.markerIconOptions) return
    //   const zoom = mapRef.value.getZoom()
    //   const { patternData } = props
    //   if (!patternData) return
    //   const arr = []
    //   for (let i = 0; i < patternList.length; i++) {
    //     const item = patternList[i]
    //     const keyValue = state.markerIconOptions![item.moduleId]?.key as keyof AssetHomeMarkerData
    //     const phase = item.phase

    //     if (item.moduleCode === 'Distribution' && !state.distributionMarker?.[item.id]) {
    //       // 判断配置绘制层级
    //       if (
    //         zoom < patternData![item.moduleId].modelConfigDataVO?.base?.minScale ||
    //         zoom > patternData![item.moduleId].modelConfigDataVO?.base?.maxScale
    //       )
    //         return

    //       state.distributionMarker[item.id] = item
    //       const markers = new aMapRef.value.LabelMarker({
    //         position: phase.coordinates,
    //         name: item?.name,
    //         icon: {
    //           type: 'image',
    //           image: state.markerIconOptions![item.moduleId]?.icons[item?.[keyValue]]?.iconUrl,
    //           size: state.markerIconOptions![item.moduleId]?.icons[item?.[keyValue]]?.iconSize
    //         },
    //         extData: item ? { ...item, active: false } : { active: false },
    //         zooms:
    //           state.markerIconOptions![item.moduleId].zooms?.length &&
    //           state.markerIconOptions![item.moduleId].zooms
    //       })
    //       markers.on('rightclick', handleRightClickPatterMarker)
    //       markers.on('click', handleClickPatterMarker)
    //       arr.push(markers)
    //     }
    //   }
    //   distribution.value.add(arr)
    //   distributionBool.value = false
    // }

    //  绘制灯杆
    const lamppostDraw = async (patternList: Record<string, any>[]) => {
      if (!patternList?.length || !state.markerIconOptions) return
      const zoom = mapRef.value.getZoom()
      const { patternData } = props
      if (!patternData) return
      const arr = []
      for (let i = 0; i < patternList.length; i++) {
        const item = patternList[i]
        const keyValue = state.markerIconOptions![item.moduleId]?.key as keyof AssetHomeMarkerData
        const phase = item.phase

        if (item.moduleCode === 'LampPost' && !state.lamppostMarker?.[item.id]) {
          // 判断配置绘制层级
          if (
            zoom < patternData![item.moduleId].modelConfigDataVO?.base?.minScale ||
            zoom > patternData![item.moduleId].modelConfigDataVO?.base?.maxScale
          )
            return

          state.lamppostMarker[item.id] = item
          const markers = new aMapRef.value.LabelMarker({
            position: phase.coordinates,
            name: item?.name,
            // 判断是灯的话层级 要覆盖在灯杆上
            zIndex: item?.moduleCode === 'LampBase' ? 13 : 12,
            icon: {
              type: 'image',
              image: state.markerIconOptions![item.moduleId]?.icons[item?.[keyValue]]?.iconUrl,
              size: state.markerIconOptions![item.moduleId]?.icons[item?.[keyValue]]?.iconSize,
              offset:
                item?.moduleCode === 'LampBase' && state.lampPostModuleId
                  ? [
                      0,
                      state.markerIconOptions![state.lampPostModuleId]?.icons[item?.[keyValue]]
                        .offset[1] * 0.6
                    ]
                  : undefined
            },
            text: {
              content: item?.name,
              direction: 'top',
              zooms: [18, 20],
              style: {
                fillColor: styles.successColor,
                strokeColor: styles.whiteColor
              }
            },
            extData: item ? { ...item, active: false } : { active: false },
            zooms:
              state.markerIconOptions![item.moduleId].zooms?.length &&
              state.markerIconOptions![item.moduleId].zooms
          })
          arr.push(markers)
          markers.on('click', handleClickPatterMarker)
        }
      }
      lamppost.value.add(arr)
    }

    //  绘制灯
    const lampDraw = async (patternList: Record<string, any>[]) => {
      if (!patternList?.length || !state.markerIconOptions) return
      const zoom = mapRef.value.getZoom()
      const { patternData } = props
      if (!patternData) return
      const arr = []
      for (let i = 0; i < patternList.length; i++) {
        const item = patternList[i]
        const keyValue = state.markerIconOptions![item.moduleId]?.key as keyof AssetHomeMarkerData
        const phase = item.phase

        if (item.moduleCode === 'LampBase' && !state.lampMarker?.[item.id]) {
          // 判断配置绘制层级

          if (
            zoom < patternData![item.moduleId].modelConfigDataVO?.base?.minScale ||
            zoom > patternData![item.moduleId].modelConfigDataVO?.base?.maxScale
          )
            return

          state.lampMarker[item.id] = item
          const markers = new aMapRef.value.LabelMarker({
            position: phase.coordinates,
            name: item?.name,
            // 判断是灯的话层级 要覆盖在灯杆上
            zIndex: item?.moduleCode === 'LampBase' ? 13 : 12,
            icon: {
              type: 'image',
              image: state.markerIconOptions![item.moduleId]?.icons[item?.[keyValue]]?.iconUrl,
              size: state.markerIconOptions![item.moduleId]?.icons[item?.[keyValue]]?.iconSize,
              offset:
                item?.moduleCode === 'LampBase' && state.lampPostModuleId
                  ? [
                      0,
                      state.markerIconOptions![state.lampPostModuleId]?.icons[item?.[keyValue]]
                        .offset[1] * 0.6
                    ]
                  : undefined
            },
            extData: item ? { ...item, active: false } : { active: false },
            zooms:
              state.markerIconOptions![item.moduleId].zooms?.length &&
              state.markerIconOptions![item.moduleId].zooms
          })
          arr.push(markers)
          markers.on('click', handleClickPatterMarker)
        }
      }
      lamp.value.add(arr)
    }

    //  绘制名称灯
    const lamptitleDraw = async (patternList: Record<string, any>[]) => {
      if (!patternList?.length || !state.markerIconOptions) return
      const zoom = mapRef.value.getZoom()
      const { patternData } = props
      if (!patternData) return
      const arr = []
      for (let i = 0; i < patternList.length; i++) {
        const item = patternList[i]
        const phase = item.phase

        if (item.moduleCode === 'LampBase' && !state.lampTitleMarker?.[item.id]) {
          // 判断配置绘制层级
          if (
            zoom < patternData![item.moduleId].modelConfigDataVO?.base?.minScale ||
            zoom > patternData![item.moduleId].modelConfigDataVO?.base?.maxScale
          )
            return

          state.lampTitleMarker[item.id] = item
          const markers = new aMapRef.value.LabelMarker({
            position: phase.coordinates,
            name: item?.name,
            // 判断是灯的话层级 要覆盖在灯杆上
            zIndex: item?.moduleCode === 'LampBase' ? 13 : 12,
            text: {
              content: item?.name,
              direction: 'top',
              zooms: [25, 20],
              style: {
                fillColor: styles.successColor,
                strokeColor: styles.whiteColor
              },
              offset: [0, -20]
            },
            extData: item ? { ...item, active: false } : { active: false },
            zooms:
              state.markerIconOptions![item.moduleId].zooms?.length &&
              state.markerIconOptions![item.moduleId].zooms
          })
          arr.push(markers)
        }
      }
      lamptitle.value.add(arr)
    }

    // 根据传入数组渲染对应的图案
    const handleDrawPattern = async (patternList: Record<string, any>[]) => {
      if (!patternList?.length || !state.markerIconOptions) return
      const { activeOptionsBar } = props

      //  当灯跟杆同时存在时，为ture
      const activeOptionsBarShow =
        activeOptionsBar!.indexOf('LampPost') > -1 && activeOptionsBar!.indexOf('LampBase') > -1

      // 将选中的所有回路数据转字符串 在渲染时如果有匹配的 则高亮 否则则正常展示
      const activeLoopIds = JSON.stringify(state.activePatternPolylineId)

      // 先把已有的点或线更新数据
      patternList?.forEach((item: Record<string, any>) => {
        if (item.moduleCode === 'DistributionLoop' && state.patternPolyline![item?.id]) {
          const phase = item.phase ? item.phase : null
          state.patternPolyline![item.id].setExtData(item)
          state.patternPolyline![item.id].setPath(phase.coordinates || [])
          return
        }
        if (state.patternMarker?.[item?.moduleId]?.[item?.id]) {
          const phase = item.phase ? item.phase : null
          state.patternMarker![item.moduleId][item.id].setPosition(phase.coordinates)
          state.patternMarker![item.moduleId][item.id].setName(item?.name)
          // LampPost
          if (activeOptionsBarShow && item.moduleCode === 'LampBase') {
            state.patternMarker![item.moduleId][item.id].setText({
              content: ''
            })
          } else {
            state.patternMarker![item.moduleId][item.id].setText({
              content: item?.name
            })
          }
        }
      })

      // 如果当前的选中的图案放大了 则缩小 如果没放大 则不执行if操作
      const activeMarkerExtData = state.activePatternMarker?.getExtData?.()

      const patternPolyline: AssetHomeMapStateType['patternPolyline'] = {}

      // 生成新的点和线
      state.patternMarker = patternList?.reduce(
        (patternMarker: AssetHomeMapStateType['patternMarker'], item: Record<string, any>) => {
          let content = null
          if (activeOptionsBarShow && item.moduleCode === 'LampBase') {
            content = ''
          } else {
            content = item?.name
          }
          // 将已有的数据过滤并返回 无需再次生成
          if (
            item.moduleCode === 'DistributionLoop' &&
            item.id &&
            state.patternPolyline![item.id]
          ) {
            patternPolyline![item.id] = state.patternPolyline![item.id]
            return patternMarker
          }
          if (state.patternMarker?.[item?.moduleId]?.[item?.id]) {
            if (patternMarker![item.moduleId]) {
              patternMarker![item.moduleId][item.id] =
                state.patternMarker?.[item.moduleId]?.[item.id]
            } else {
              patternMarker![item.moduleId] = {
                [item.id]: state.patternMarker?.[item.moduleId]?.[item.id]
              }
            }
            return patternMarker
          }

          const phase = item.phase ? item.phase : null
          // 当没有配置经纬度路经点时则不去生成图形
          if (!phase) return patternMarker
          // 如果当前为回路则生成折线
          if (phase.type === 'polyline' || phase.type === 'multiPolyline') {
            const loopKeyValue = state.loopOptions![item.moduleId]?.key as keyof AssetHomeMarkerData
            // 找不到匹配的折线配置就return
            if (!loopKeyValue) return patternMarker
            const activeFlag = activeLoopIds?.includes(item.id)
            const polyline = new aMapRef.value.Polyline({
              // map: mapRef.value,
              path: phase.coordinates || [],
              title: item?.name,
              cursor: 'pointer',
              lineJoin: 'round',
              lineCap: 'round',
              strokeColor:
                state.loopOptions![item.moduleId]?.settings[item?.[loopKeyValue]]?.lineColor,
              strokeOpacity:
                state.loopOptions![item.moduleId]?.settings[item?.[loopKeyValue]]?.lineOpacity,
              strokeWeight: activeFlag
                ? state.loopOptions![item.moduleId]?.settings[item?.[loopKeyValue]]?.selectLineWidth
                : state.loopOptions![item.moduleId]?.settings[item?.[loopKeyValue]]?.lineWidth,
              zooms:
                state.loopOptions![item.moduleId].zooms?.length &&
                state.loopOptions![item.moduleId].zooms,
              extData: item
            })
            patternPolyline![item.id] = polyline
            polyline.on('click', handleClickPatternPolyline)
            return patternMarker
          }
          const keyValue = state.markerIconOptions![item.moduleId]?.key as keyof AssetHomeMarkerData
          if (phase.type !== 'point' || !keyValue || !state.markerIconOptions![item.moduleId])
            return patternMarker
          const marker = new aMapRef.value.LabelMarker({
            position: phase.coordinates,
            name: item?.name,
            // 判断是灯的话层级 要覆盖在灯杆上
            zIndex: item?.moduleCode === 'LampBase' ? 13 : 12,
            icon: {
              type: 'image',
              image: state.markerIconOptions![item.moduleId]?.icons[item?.[keyValue]]?.iconUrl,
              size: state.markerIconOptions![item.moduleId]?.icons[item?.[keyValue]]?.iconSize,
              offset:
                // state.markerIconOptions![item.moduleId]?.icons[item?.[keyValue]]?.offset
                item?.moduleCode === 'LampBase' && state.lampPostModuleId
                  ? [
                      0,
                      state.markerIconOptions![state.lampPostModuleId]?.icons[item?.[keyValue]]
                        .offset[1] * 0.6
                    ]
                  : undefined
            },
            text: {
              content,
              direction: 'top',
              zooms: [18, 20],
              style: {
                fillColor: styles.successColor,
                strokeColor: styles.whiteColor
              }
            },
            extData: item ? { ...item, active: false } : { active: false },
            zooms:
              state.markerIconOptions![item.moduleId].zooms?.length &&
              state.markerIconOptions![item.moduleId].zooms
          })
          if (patternMarker![item.moduleId]) {
            patternMarker![item.moduleId][item.id] = marker
          } else {
            patternMarker![item.moduleId] = { [item.id]: marker }
          }

          if (item?.moduleCode === 'Distribution') {
            marker.on('rightclick', handleRightClickPatterMarker)
          }
          marker.on('click', handleClickPatterMarker)
          if (
            activeMarkerExtData?.id === item?.id &&
            activeMarkerExtData?.moduleId === item?.moduleId
          )
            handleChangeEnlargeMarker({ target: marker })

          return patternMarker
        },
        {}
      )
      state.patternPolyline = patternPolyline

      // // 清理线并重新添加进图层展示
      // const patternPolylineList = Values(state.patternPolyline)
      // if (patternPolylineList?.length) {
      //   state.polylineLayer!.clear()
      //   state.polylineLayer!.add(Values(state.patternPolyline))
      //   state.polylineLayer!.show()
      // }

      // 清理点并重新添加进图层展示
      // state.markerLayer?.clear?.()
      // state.markerLayer?.add?.(
      //   Values(state.patternMarker)
      //     ?.map((item: Record<string, any>) => Values(item))
      //     .flat()
      // )
      // state.markerLayer?.show?.()
    }

    // 根据父元素传入的moduleid查询当前地图可视区域内的所有配电设施路灯及灯具marker
    const handleSearchMapMarkerByModuleId = async () => {
      const { activeModules } = props

      const bounds = mapRef.value.getBounds()
      // 西北（左上）
      const northWest = bounds.getNorthWest()
      // 东南（右下）
      const southEast = bounds.getSouthEast()
      const zoom = mapRef.value.getZoom()
      if (activeModules?.length) {
        setTimeout(() => {
          const { activeOptionsBar } = props

          if (activeOptionsBar!.indexOf('Distribution') > -1) {
            distribution.value.show()
          } else {
            distribution.value.hide()
          }

          if (activeOptionsBar!.indexOf('DistributionLoop') > -1) {
            state.lineGroup && state.lineGroup.show()
          } else {
            state.lineGroup && state.lineGroup.hide()
          }

          if (activeOptionsBar!.indexOf('LampPost') > -1) {
            lamppost.value.show()
          } else {
            lamppost.value.hide()
          }
          if (activeOptionsBar!.indexOf('LampBase') > -1) {
            lamp.value.show()
            lamptitle.value.show()
          } else {
            lamp.value.hide()
            lamptitle.value.hide()
          }
          if (
            activeOptionsBar!.indexOf('LampPost') > -1 &&
            activeOptionsBar!.indexOf('LampBase') > -1
          ) {
            lamptitle.value.hide()
          }
        }, 50)

        const res = await store.dispatch('assetHome/GetAssetHomeBaseDataByModuleId', {
          moduleIds: activeModules?.join(','),
          leftLatitude: northWest.lat,
          leftLongitude: northWest.lng,
          rightLatitude: southEast.lat,
          rightLongitude: southEast.lng,
          level: zoom,
          specialCode: 'asset_home'
        })
        lamppostDraw(res?.data)
        lampDraw(res?.data)
        lamptitleDraw(res?.data)
        handleDrawPattern(res?.data)
      }
    }

    // 根据传入的坐标点数据对比当前选中的是否一致 不一致则切换一致（场景用于多点重合一个位置）
    const handleChangeActivePatternMarker = (record: Record<string, any>) => {
      if (state.patternMarker![record?.moduleId]) {
        if (state.patternMarker![record?.moduleId][record?.id]) {
          if (state.activePatternMarker) {
            handleChangeEnlargeMarker({ target: state.activePatternMarker })
          }
          state.activePatternMarker = state.patternMarker![record?.moduleId][record?.id]
          // 如果当前替换的还是原来的则恢复其放大状态
          if (!state.activePatternMarker!.getExtData()?.active)
            handleChangeEnlargeMarker({ target: state.activePatternMarker })
        }
      }
    }

    // 清空当前绘制点并重新绘制设备点
    const handleDrawEquipmentPoint = (patternList: Record<string, any>[]) => {
      if (patternList?.length) {
        const firstDataParse = patternList[0]?.phase
        if (!firstDataParse?.coordinates?.length) return
        const mapZoom = mapRef.value.getZoom()
        if (
          mapZoom >
            props.patternData?.[patternList[0]?.moduleId]?.modelConfigDataVO?.base?.minScale! &&
          mapZoom <
            props.patternData?.[patternList[0]?.moduleId]?.modelConfigDataVO?.base?.maxScale!
        ) {
          mapRef.value.setCenter(firstDataParse.coordinates, false, 0)
        } else {
          mapRef.value.setZoomAndCenter(
            props.patternData?.[patternList[0]?.moduleId]?.modelConfigDataVO?.base?.minScale ??
              mapRef.value.getZoom(),
            firstDataParse.coordinates,
            false,
            0
          )
        }
      }
    }

    // 清空当前查询的设备点 并重新绘制当前可视区域的所有坐标点
    const handleClearEquipmentPoint = () => {
      // lineBool.value = true
      // 先移除所有的坐标点和线
      // handleClearDrawPattern()
      handleSearchMapMarkerByModuleId()
    }

    // 初始化map事件
    async function initAMap() {
      // mapRef.value.addLayer(aMapRef.value.createDefaultLayer())
      await props.initCallback()
      loadRef.value!.close()
      // 初始化折线图层
      // state.polylineLayer = new aMapRef.value.CustomLayer({
      //   visible: true
      // })
      // mapRef.value.add(state.polylineLayer)
      // 初始化labelmarker图层
      // state.markerLayer = new aMapRef.value.LabelsLayer({
      //   visible: true,
      //   collision: false,
      //   allowCollision: false
      // })
      // mapRef.value.add(state.markerLayer)
      // 为地图绑定拖拽结束事件  结束后要去触发请求 查询当前显示区域内的所有选中的值
      mapRef.value.on('moveend', handleSearchMapMarkerByModuleId)
      mapRef.value.on('zoomend', () => {
        handleSearchMapMarkerByModuleId()
        props.getMapZoom?.()

        // if (mapRef.value.getZoom() >= 18) {
        //   console.log('mapRef.value.showLabel = true', mapRef.value);

        //   mapRef.value.setShowLabel(true);
        // } else {
        //   mapRef.value.showLabel = false
        // }
      })

      //  灯杆图层
      lamppost.value = new aMapRef.value.LabelsLayer({
        visible: true,
        collision: false,
        allowCollision: false
      })
      mapRef.value.add(lamppost.value)
      //  灯图层
      lamp.value = new aMapRef.value.LabelsLayer({
        visible: true,
        collision: false,
        allowCollision: false
      })
      mapRef.value.add(lamp.value)
      //  灯名称图层
      lamptitle.value = new aMapRef.value.LabelsLayer({
        visible: true,
        collision: false,
        allowCollision: false
      })
      mapRef.value.add(lamptitle.value)
      //  配电设施图层
      distribution.value = new aMapRef.value.LabelsLayer({
        visible: true,
        collision: false,
        allowCollision: false
      })
      mapRef.value.add(distribution.value)

      // const { activeModules } = props
      // const bounds = mapRef.value.getBounds()
      // // 西北（左上）
      // const northWest = bounds.getNorthWest()
      // // 东南（右下）
      // const southEast = bounds.getSouthEast()
      // const zoom = mapRef.value.getZoom()
      // //  获取所有箱变和回路的数据
      // const res1 = await store.dispatch('assetHome/GetAssetHomeBaseDataByModuleIdWhole', {
      //   moduleIds: `${activeModules[0]},${activeModules[1]}`,
      //   leftLatitude: northWest.lat,
      //   leftLongitude: northWest.lng,
      //   rightLatitude: southEast.lat,
      //   rightLongitude: southEast.lng,
      //   level: zoom
      // })
      // handPolyline(res1?.data)
      // distributionDraw(res1?.data)
    }

    onMounted(() => {
      loadRef.value = ElLoading.service({
        target: `#${props.id}`,
        text: '加载中'
      })
    })

    onBeforeUnmount(() => {
      mapRef.value.clearMap()
      mapRef.value.destroy()
    })

    expose({
      map: mapRef,
      aMap: aMapRef,
      amapIcon: amapIconRef,
      restCenter: handleRestMapCenter,
      setMapInfo: handleSetMapInfo,
      renderWorkAreaPolygon: handleGeneratePolygon,
      toggleWorkAreaPolygonVisible: handleChangePolygonVisible,
      showAreaPolygonByAreaId: handleShowAreaPolygonByAreaId,
      searchMapMarker: handleSearchMapMarkerByModuleId,
      clearActiveMarkerEvent: handleClearActiveMarkerEvent,
      generateMarkerIcon: handleGenerateMarkerIcon,
      getPatterMarkerInfo: handleGetPatterMarkerInfoBy,
      changeActivePatternMarker: handleChangeActivePatternMarker,
      changeActivePatternPolyline: handleChangeActivePatternPolyline,
      drawEquipmentPoint: handleDrawEquipmentPoint,
      clearEquipmentPoint: handleClearEquipmentPoint
    })
    return () => (
      <>
        <section id={props.id} ref={mapDomRef}></section>
      </>
    )
  }
})
